<template>
  <div class="page-container fullpage">
    <el-card>
          <div class="admin-header" style="position:relative;">
            <h3>用户管理</h3>
            <div style="position:absolute; right:16px; top:6px">
              <el-button type="text" size="small" @click="logout">退出</el-button>
            </div>
          </div>

          <el-table :data="users" style="width:100%; margin-top:12px">
            <el-table-column :label="'用户名'">
              <template #default="{ row }">
                {{ row.userName || row.username || row.name || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="enName" label="英文名" />
            <el-table-column prop="mobile" label="手机" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="birthday" label="生日" />
            <el-table-column label="操作" width="240">
              <template #default="{ row }">
                <div style="display:flex;gap:8px;justify-content:flex-end">
                  <el-button type="primary" size="small" @click="viewUser(row)">查看</el-button>
                  <el-button type="warning" size="small" @click="editUser(row)">修改</el-button>
                  <el-button type="danger" size="small" @click="deleteUser(row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../utils/api'

const users = ref<Array<any>>([])
const router = useRouter()

const load = async () => {
  try {
    const resp: any = await api.get('/users')
    if (resp && resp.operationResult === 'SUCC') {
      users.value = resp.data || []
    } else if (Array.isArray(resp)) {
      users.value = resp
    } else {
      users.value = resp?.data || []
    }
  } catch (err) {
    console.error('load users err', err)
  }
}

onMounted(() => { load() })

const viewUser = (row: any) => { try { router.push({ path: `/admin/users/view/${encodeURIComponent(row.userName || row.username || '')}` }) } catch(e) {} }
const editUser = (row: any) => { try { router.push({ path: `/admin/users/edit/${encodeURIComponent(row.userName || row.username || '')}` }) } catch(e) {} }
const tryDeleteFallbacks = async (username: string) => {
  // Try several possible backend endpoints until one succeeds or all fail.
  const attempts = [
    async () => await api.delete('/user', { params: { username } }),
    async () => await api.delete(`/user/${encodeURIComponent(username)}`),
    async () => await api.post('/user/delete', { username }),
    async () => await api.post('/users/delete', { username })
  ]

  let lastErr: any = null
  for (const fn of attempts) {
    try {
      const r: any = await fn()
      // consider success if operationResult === 'SUCC' or HTTP OK/204
      if (!r) continue
      if (r.operationResult === 'SUCC' || r?.success === true) return { ok: true, resp: r }
      // if response is array or object without operationResult, still accept 200-level
      return { ok: true, resp: r }
    } catch (e) {
      lastErr = e
      // continue to next attempt
      console.warn('delete attempt failed, trying next', e)
    }
  }
  return { ok: false, err: lastErr }
}

const deleteUser = async (row: any) => {
  const username = row.userName || row.username || ''
  if (!username) return
  try {
    const result = await tryDeleteFallbacks(username)
    if (result.ok) {
      // refresh
      await load()
    } else {
      console.error('all delete attempts failed', result.err)
    }
  } catch (err) { console.error('delete error', err) }
}

const logout = () => {
  try { localStorage.removeItem('username'); localStorage.removeItem('role') } catch (e) {}
  try { router.push('/login') } catch (e) {}
}

// no top-level goBack; admin pages will provide their own return-to-admin-users navigation
</script>

<style scoped>
.admin-header h3 { margin: 0 }
.muted { color: var(--muted-2, #8b95a3); margin-top:6px }
.page-container { padding: 16px }
</style>
